import mysql.connector
import redis


def save_to_redis(data):
    # 连接到 Redis 服务器
    r = redis.Redis(host='localhost', port=6379, db=0)
    # 遍历数据，将每行数据存储到 Redis 中
    for row in data:
        # 假设每个用户有一个唯一的 id 作为键，其他信息作为值存储
        id = row[0]  # 假设第一列是用户 id
        info = str(row)  # 将整行数据转换为字符串作为值
        r.set(id,info)
    print("数据已成功存储到 Redis")


def fetch_data_from_sys_user():
    cnx = mysql.connector.connect(user='root', password='123456', host='localhost', port=3307, database='supermarket')
    cursor = cnx.cursor()
    cursor.execute("SELECT * FROM sys_user")
    data = cursor.fetchall()
    cursor.close()
    cnx.close()
    return data


def fetch_data_from_role():
    cnx = mysql.connector.connect(user='root', password='123456', host='localhost', port=3307, database='supermarket')
    cursor = cnx.cursor()
    cursor.execute("select * from sys_role")
    data = cursor.fetchall()
    cursor.close()
    cnx.close()
    return data


if __name__ == "__main__":
    data_user = fetch_data_from_sys_user()
    data_role = fetch_data_from_role()
    save_to_redis(data_user)
    save_to_redis(data_role)

